import { NextRequest, NextResponse } from 'next/server';
import { promises as fs } from 'fs';
import path from 'path';

interface ImageRecord {
  id: string;
  name: string;
  path: string;
  size: number;
  createTime: string;
  imageData: string; // base64编码的图片数据
  mimeType: string; // 图片MIME类型
}

// 支持的图片格式
const IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];

export async function GET(request: NextRequest) {
  try {
    // 获取查询参数
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const pageSize = parseInt(searchParams.get('pageSize') || '12');
    const sortBy = searchParams.get('sortBy') || 'createTime';
    const sortOrder = searchParams.get('sortOrder') || 'desc';

    // 限制每页最大数量，避免内存问题
    const maxPageSize = Math.min(pageSize, 24);
    
    // 构建文件路径
    const fileLogPath = path.join(process.cwd(), 'sd-model', 'file-log');
    
    // 检查目录是否存在
    try {
      await fs.access(fileLogPath);
    } catch (error) {
      // 如果目录不存在，返回空数组
      return NextResponse.json({
        images: [],
        total: 0,
        page,
        pageSize,
        totalPages: 0
      });
    }

    // 读取目录内容
    const files = await fs.readdir(fileLogPath);
    
    // 过滤图片文件并获取文件信息
    const imageFiles: ImageRecord[] = [];
    
    for (const file of files) {
      const filePath = path.join(fileLogPath, file);
      const ext = path.extname(file).toLowerCase();
      
      // 检查是否为图片文件
      if (IMAGE_EXTENSIONS.includes(ext)) {
                 try {
           const stats = await fs.stat(filePath);
           
           // 读取图片文件并转换为base64
           const imageBuffer = await fs.readFile(filePath);
           const imageData = imageBuffer.toString('base64');
           
           // 获取图片MIME类型
           const getMimeType = (extension: string): string => {
             switch (extension.toLowerCase()) {
               case '.png':
                 return 'image/png';
               case '.jpg':
               case '.jpeg':
                 return 'image/jpeg';
               case '.gif':
                 return 'image/gif';
               case '.webp':
                 return 'image/webp';
               case '.bmp':
                 return 'image/bmp';
               default:
                 return 'image/png';
             }
           };
           
           const mimeType = getMimeType(ext);
           
           imageFiles.push({
             id: file,
             name: file,
             path: filePath,
             size: stats.size,
             createTime: stats.birthtime.toISOString(),
             imageData: imageData,
             mimeType: mimeType
           });
        } catch (error) {
          console.warn(`无法读取文件信息: ${filePath}`, error);
        }
      }
    }

    // 排序
    imageFiles.sort((a, b) => {
      let comparison = 0;
      
             switch (sortBy) {
         case 'name':
           comparison = a.name.localeCompare(b.name);
           break;
         case 'size':
           comparison = a.size - b.size;
           break;
         case 'createTime':
         default:
           const timeA = typeof a.createTime === 'string' ? new Date(a.createTime).getTime() : a.createTime.getTime();
           const timeB = typeof b.createTime === 'string' ? new Date(b.createTime).getTime() : b.createTime.getTime();
           comparison = timeA - timeB;
           break;
       }
      
      return sortOrder === 'desc' ? -comparison : comparison;
    });

    // 计算分页
    const total = imageFiles.length;
    const totalPages = Math.ceil(total / maxPageSize);
    const startIndex = (page - 1) * maxPageSize;
    const endIndex = startIndex + maxPageSize;
    const paginatedImages = imageFiles.slice(startIndex, endIndex);

    return NextResponse.json({
      images: paginatedImages,
      total,
      page,
      pageSize: maxPageSize,
      totalPages,
      sortBy,
      sortOrder
    });

  } catch (error) {
    console.error('获取图片记录错误:', error);
    return NextResponse.json(
      { 
        error: '获取图片记录失败',
        detail: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    );
  }
}
